package com.maotouying.recycleviewtest.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.maotouying.recycleviewtest.R;
import com.maotouying.recycleviewtest.beans.ItemBean;

import java.util.List;

/**
 * @author mingtai
 * @description
 * @time 2020/8/21 23:20
 */

public abstract class RecyclerViewBaseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final List<ItemBean> mData;
    public OnItemClickListener mOnItemClickListener;

    // 通过构造方法传递数据进来
    protected RecyclerViewBaseAdapter(List<ItemBean> mData) {
        this.mData = mData;
    }


    /**
     * 用于创建条目的view
     *
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = getSubView(parent, viewType);
        return new ListViewAdapter.InnerHolder(view);
    }

    protected abstract View getSubView(ViewGroup parent, int viewType);


    /**
     * 用于绑定holder，一般用来设置数据
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        ((InnerHolder) holder).setData(mData.get(position), position);
    }


    /**
     * 返回条目的个数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        if (mData != null) {
            return mData.size();
        }
        return 0;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        // 设置一个监听   也就是设置一个接口，回调的接口
        this.mOnItemClickListener = listener;
    }

    /**
     * 编写回调的步骤
     * 1、创建接口
     * 2、定义接口内部的方法
     * 3、提供设置接口的方法，  外部设置接口，外部实现此接口
     * 4、接口方法的调用
     */

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public class InnerHolder extends RecyclerView.ViewHolder {

        private ImageView mIcon;
        private TextView mTitle;
        public int mPosition;

        public InnerHolder(@NonNull View itemView) {
            super(itemView);

            // 找到条目控件
            mIcon = itemView.findViewById(R.id.icon);
            mTitle = itemView.findViewById(R.id.title);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(mPosition);
                    }
                }
            });
        }


        // 这个方法用来设置数据
        public void setData(ItemBean itemBean, int position) {

            this.mPosition = position;

            //    开始设置数据
            mIcon.setImageResource(itemBean.icon);
            mTitle.setText(itemBean.title);

        }


    }


}
